package com.hjs.pacloudservice.service.Impl;

import com.hjs.pacloudservice.pojo.File;
import com.hjs.pacloudservice.remote.FileUploadRemote;
import com.hjs.pacloudservice.service.IFileUploadService;
import com.hjs.pacloudservice.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.text.DecimalFormat;
import java.util.function.Predicate;
import java.util.stream.Stream;

/**
 * @auther hanjinsong
 * @create 2019-08-21 19:11
 */

@Service
public class FileUploadService implements IFileUploadService {

    @Value("${locationdir}")
    private Path rootLocation;


    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private FileUploadRemote fileUploadRemote;

    @Override
    public int insert(File file) {
        return fileUploadRemote.insert(file);
    }

    @Override
    public File select(Integer id) {
        return null;
    }

    @Override
    public void init() {
        if (!(new java.io.File("upload-dir").exists())) {
            try {
                Files.createDirectories(rootLocation);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void store(MultipartFile file) throws IOException {
        String filename = StringUtils.cleanPath(file.getOriginalFilename());
        //sender.send(filename);
        InputStream inputStream = file.getInputStream();
        //Transf transf = new Transf(inputStream,filename);
        //sender.send(transf);//发送至mq
        Files.copy(inputStream, this.rootLocation.resolve(filename), StandardCopyOption.REPLACE_EXISTING);
        File file1 = new File();
        file1.setName(filename);
        file1.setSize(fileSizeConver(file.getSize()));
        fileUploadRemote.insert(file1);
        redisUtils.set(filename,"http://localhost:8080/files/"+filename);
    }

    public static String fileSizeConver(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize="0B";
        if(fileS==0){
            return wrongSize;
        }
        if (fileS < 1024){
            fileSizeString = df.format((double) fileS) + "B";
        }
        else if (fileS < 1048576){
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        }
        else if (fileS < 1073741824){
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        }
        else{
            fileSizeString = df.format((double) fileS / 1073741824) + "GB";
        }
        return fileSizeString;
    }

    /**
     * 列出upload-dir下面所有文件
     * @return
     */
    @Override
    public Stream<Path> loadAll() throws IOException {
        return Files.walk(this.rootLocation, 1)
                .filter(new Predicate<Path>()
                {
                    @Override
                    public boolean test(Path path)
                    {
                        return !path.equals(rootLocation);
                    }
                });
    }

    @Override
    public Path load(String filename)
    {
        return rootLocation.resolve(filename);
    }

    /**
     * 获取文件资源
     * @param filename 文件名
     * @return Resource
     */
    @Override
    public Resource loadAsResource(String filename) throws MalformedURLException {

        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        return resource;

    }

    /**
     * 删除upload-dir目录所有文件
     */
    @Override
    public void deleteAll()
    {
        FileSystemUtils.deleteRecursively(rootLocation.toFile());
    }

}
